#include "package.h"
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include "bgc/include/gc.h"

static CFPackage * pkg_hash_table[MAX_PACKAGE_SIZE];


static int hashSymbolTableLookup (char * string){
	int value=0, i=0, length = strlen(string);
	for (i = 0; i<length; i++)
				value += (int) string[i];
	return value % MAX_PACKAGE_SIZE;
}



CFPackage * PKGGetPackage (char * name){
	int i=hashSymbolTableLookup(name);
	CFPackage * iterator = pkg_hash_table[i];
	if (iterator == NULL)
		{
			return iterator;
		}
	else{
		while(!(iterator->next == NULL))
			{
				if(!strcmp(iterator->name, name))
					{PKGError("Package already exists");
					 return NULL;}
				iterator = iterator->next;
			}
		if(strcmp(iterator->name, name))
		  return NULL;
		else
  		return iterator;
	}
}

CFPackage * PKGCreatePackage (char * name){
	int i=hashSymbolTableLookup(name);
	CFPackage * iterator = pkg_hash_table[i];
	if (iterator == NULL)
		{
			pkg_hash_table[i] = MMPackage(name);
			return pkg_hash_table[i];
		}
	else{
		while(!(iterator->next == NULL))
			{
				if(!strcmp(iterator->name, name))
					{PKGError("Package already exists");
					 return NULL;}
				iterator = iterator->next;
			}
		iterator->next = MMPackage(name);
		return iterator->next;
	}
}


CFSymbol * PKGAddSymbol (CFSymbol * object, char * name){
	CFPackage * pkg = PKGGetPackage(name);
	int i=strlen(MMSymbolName(object));
	CFSymbol * iterator = pkg->hashTable[i];
	if (iterator == NULL)
		{pkg->hashTable[i] = object;
		 return object;}
	else{
		while(!(iterator->hashvalue == NULL))
			{if(!strcmp(MMSymbolName(iterator), MMSymbolName(object)))
				{return iterator;}
			 iterator = iterator->hashvalue;}
		iterator->hashvalue = object;
		return object;
	}
	
}

void PKGInit (void){
	CFPackage * std = PKGCreatePackage("System");
	PKGSystemPackage = std;
	
	PKGKeywordPackage = PKGCreatePackage("Keyword");
	
	PKGSwitchCurrentPackage(std)
}
